package run.newbug.jt.service;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import run.newbug.jt.mapper.ItemDescMapper;
import run.newbug.jt.mapper.ItemMapper;
import run.newbug.jt.pojo.Item;
import run.newbug.jt.pojo.ItemDesc;
import run.newbug.jt.vo.ItemVO;
import run.newbug.jt.vo.PageResult;

import java.util.List;
@Component
public class ItemServiceImpl implements ItemService{
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private ItemDescMapper itemDescMapper;

    @Override
    public PageResult getItemList(PageResult pageResult) {
        IPage iPage = new Page(pageResult.getPageNum(),pageResult.getPageSize());
        Boolean queBoo = StringUtils.hasLength(pageResult.getQuery());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like(queBoo, "username", pageResult.getQuery());
        IPage iPage1 = itemMapper.selectPage(iPage,queryWrapper);
        pageResult.setRows(iPage1.getRecords());
//        pageResult.setTotal(userMapper.selectCount(null).longValue());
        pageResult.setTotal(iPage1.getTotal());
        return pageResult;
    }

    @Override
    public void updateItemStatus(Item item) {
        itemMapper.updateById(item);
        return;
    }

    @Override
    public void deleteItemById(Integer id) {
        itemMapper.deleteById(id);
        itemDescMapper.deleteById(id);
        return;
    }

    @Override
    public Item getById(Integer id) {
        return itemMapper.selectById(id);
    }

    @Override
    public void updateItem(Item item) {
        itemMapper.updateById(item);
    }

    @Override
    @Transactional
    public void saveItem(ItemVO itemVO) {
        Item item = itemVO.getItem();
        item.setStatus(true);
        itemMapper.insert(item);


//        QueryWrapper<Item> queryWrapper = new QueryWrapper();
//        queryWrapper.eq("title", item.getTitle())
//                .eq("sell_point", item.getSellPoint());
//        Integer id = itemMapper.selectOne(queryWrapper).getId();
        ItemDesc itemDesc = itemVO.getItemDesc();

        itemDesc.setId(item.getId());
        itemDescMapper.insert(itemDesc);
        return;
    }
}
